﻿using System;
using System.Data;
using BusinessEntities;
using Draco.DataStructure;
using MySql.Data.MySqlClient;

namespace DataAccessLayer
{
    public class MetroDAL : DAL<MetroNode>
    {
        public override D_LinkList<MetroNode> GetElements()
        {
            D_LinkList<MetroNode> nodes = new D_LinkList<MetroNode>();

            string query = "SELECT * FROM metro";

            MySqlDataReader reader = MySqlHelper.ExecuteReader(connString, query);

            while (reader.Read())
            {
                int id = (int)reader["id"];
                string name = reader["name"].ToString();
                int x = (int)reader["x"];
                int y = (int)reader["y"];
                bool isTerminal = (int)reader["terminal"] > 0 ? true : false;
                int line1 = (int)reader["line1"];
                int line2 = (int)reader["line2"];

                MetroNode s = new MetroNode(id, name, x, y, isTerminal, line1, line2);

                nodes.Add(s);
            }

            reader.Close();

            return nodes;
        }

        public override void Insert(params object[] args)  //站名，x，y，是否起始站，所在线1，所在线2
        {
            string name = args[0] as string;
            int x = (int)args[1];
            int y = (int)args[2];
            int isTerminal = (int)args[3];
            int line1 = (int)args[4];
            int line2 = (int)args[5];
            string query = string.Format("INSERT INTO metro(name, x, y, terminal, line1, line2) VALUES ('{0}','{1}','{2}','{3}','{4}','{5}')", name, x, y, isTerminal, line1, line2);

            MySqlHelper.ExecuteNonQuery(connString, query);
        }

        public override void Update(params object[] args)
        {
            int id = (int)args[0];
            string name = args[1] as string;
            int x = (int)args[2];
            int y = (int)args[3];
            int terminal = (int)args[4];
            int line1 = (int)args[5];
            int line2 = (int)args[6];
            string query = string.Format("UPDATE metro SET name='{1}',x='{2}',y='{3}',terminal='{4}',line1='{5}',line2='{6}' WHERE id={0}", id, name, x, y, terminal, line1, line2);

            MySqlHelper.ExecuteNonQuery(connString, query);
        }

        public override void Delete(int id)
        {
            string query = string.Format("DELETE FROM metro WHERE id={0}", id);

            MySqlHelper.ExecuteNonQuery(connString, query);
        }

        public override int GetLastInsertID()
        {
            int result = 0;
            string query = "select max(id) FROM metro";
            DataRow datarow = MySqlHelper.ExecuteDataRow(connString, query);
            try
            {
                result = int.Parse(datarow[0].ToString());
            }
            catch (Exception e)
            {
                result = -1;
            }
            return result;
        }
    }
}
